//
//  DPMeWalletWithDrawViewController.swift
//  DoctorEPlus
//
//  Created by 王林波 on 2021/3/8.
//  提现

import UIKit
import IDealist

class DPMeWalletWithDrawViewController: BHBaseViewController {

    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.register(UINib.init(nibName: "DPWalletWithDrawTipCell", bundle: nil), forCellReuseIdentifier: "DPWalletWithDrawTipCell")
        view.register(UINib.init(nibName: "DPWalletBindAliAccountCell", bundle: nil), forCellReuseIdentifier: "DPWalletBindAliAccountCell")
        view.register(UINib.init(nibName: "DPWalletWithDrawInputCell", bundle: nil), forCellReuseIdentifier: "DPWalletWithDrawInputCell")
        view.bounces = false
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var footerView: DPWalletWithDrawBottomView = {
        let view = DPWalletWithDrawBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.showHeight-DPWalletWithDrawTipCell.cellHeight-DPWalletBindAliAccountCell.cellHeight-DPWalletWithDrawInputCell.cellHeight)
        return view
    }()
    
    fileprivate var infoModel: DPWalletAlipayInfoModel = DPWalletAlipayInfoModel.init()
    fileprivate var withDrawMoney: String = ""
    lazy var alipayManager: DPAlipayManager = DPAlipayManager.init()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "钱包"
        self.view.addSubview(self.tableView)
        self.tableView.tableFooterView = self.footerView
        
        self.footerView.bottomViewDidSelectIndexBlock = { [weak self] index in
            self?.view.endEditing(true)
            if index == 0 { // 提现
                if self?.infoModel.alipayNickName.isEmpty == true {
                    IDToast.id_show(msg: "请先绑定支付宝")
                    return
                }
                if self?.withDrawMoney.isEmpty == true {
                    IDToast.id_show(msg: "请输入提现金额")
                    return
                }
                if self?.withDrawMoney == "0" ||
                    self?.withDrawMoney == "0." ||
                    self?.withDrawMoney == "0.0" ||
                    self?.withDrawMoney == "0.00"{
                    IDToast.id_show(msg: "提现金额不能为0")
                    return
                }
                
                let result = DPWalletFlowManager.checkMoneyAvalid(self!.withDrawMoney)
                if result.0 == true {
                    self?.goWithDrawService()
                }else {
                    BHToast.toast(text: result.1)
                    
                }
            }else {
                
            }
        }
        
        self.loadMyBalanceService()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBind), name: NSNotification.Name(rawValue: String.alipayBindResulyNotificationKey), object: nil)
    }
    
    @objc func refreshBind() {
        self.loadMyBalanceService()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}


extension DPMeWalletWithDrawViewController: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return DPWalletWithDrawTipCell.cellHeight
        }
        else if indexPath.row == 1 {
            return DPWalletBindAliAccountCell.cellHeight
        }else {
            return DPWalletWithDrawInputCell.cellHeight
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "DPWalletWithDrawTipCell", for: indexPath) as! DPWalletWithDrawTipCell
            return cell
        }else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "DPWalletBindAliAccountCell", for: indexPath) as! DPWalletBindAliAccountCell
            cell.model = self.infoModel
            cell.bindAlipayAccountBlock = {
                DPAlipayManager.init().goAlipayAuth()
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "DPWalletWithDrawInputCell", for: indexPath) as! DPWalletWithDrawInputCell
            cell.inputMoneyTextFiled.text = self.withDrawMoney
            
            cell.maxValue = self.infoModel.cashBalance
            
            cell.didMoneyInputBlock = { [weak self] money in
                self?.withDrawMoney = money
            }
            cell.didChoseTypeBlock = { [weak self] type in 
                if  type == 0 { // 全部提现
                    if self?.infoModel.cashBalance == "0" {
                        return
                    }
                    self?.withDrawMoney = self?.infoModel.cashBalance ?? ""
                }else {
                    self?.withDrawMoney = ""
                }
                tableView.reloadData()
            }
            return cell
        }
    }
}

extension  DPMeWalletWithDrawViewController {
   
    // 获取我的余额
    func loadMyBalanceService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.wallet_user_account_url, paramters: [:]) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()

            if success == true {
                let dic = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                self.infoModel.parseDic(dic)
               
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func goWithDrawService() {
        IDLoading.id_show()
        let manager = BHHTTPClient.init()
        let dic = self.appendWithDrawDic()
        manager.post(url: String.wallet_user_withDraw_url, paramters: dic) { (success, errorMsg, responseDic) in
            if success == true {
                let resultVC = DPWalletWithDrawResultViewController.init()
                resultVC.money = self.withDrawMoney
                resultVC.account = self.infoModel.alipayNickName
                self.navigationController?.pushViewController(resultVC, animated: true)
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
     
    }
    
    func appendWithDrawDic() -> [String: Any] {
        var dic: [String: Any] = [:]
        dic["amount"] = self.withDrawMoney
        return dic
    }
}
